# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404
from models import Domains, Games
import os, re
from django.conf import settings

def index(request):
    lastgames = Games.objects.filter(has_scenario=1).select_related('domain').order_by('-game_date')[:20]
    return render_to_response('index.html',{'lastgames':lastgames})

def games(request,domain="kms.en.cx"):
    current_domain = domain or 'kms.en.cx'  
    
    domain = get_object_or_404(Domains, domain_name=current_domain)
    
    domains = Domains.objects.all().order_by('domain_name')
    for d in domains:
        d.available_scenarios = d.games_set.filter(has_scenario=1).count()
    
    games = Games.objects.filter(domain=domain).order_by('-game_date')
    print games
    
    return render_to_response('games.html',{'current_domain':current_domain, 'domains':domains,'games':games})

def scenario(request, domain=None, game_id=0):
    
    # определим человечное название игры
    game = get_object_or_404(Games, id=game_id)
    if game.can_show_scenario():
        scenario_file_name = settings.FILESTORAGE + 'original/%s/%s/%s_scenario.html' % (domain, game_id, game_id, )
        if os.path.exists(scenario_file_name):
            scenario_file = open(scenario_file_name)
            full_html = scenario_file.read().decode('utf-8')
            scenario_file.close()

            body_r = '<body.*?>(.*)</body>'
            match = re.findall(body_r, full_html, re.DOTALL | re.MULTILINE | re.IGNORECASE)
            text = match[0]

            # немножко магии замен и подстановок
            subs_pattern = '(?sm)<td background="/images/backgrounds/mainframe2.gif">.*?<a href="/"><img src="images/logos/en_logo_org.gif" width="214" height="65" border="0" /></a>.*?</td>'

            text = re.sub(subs_pattern, '', text, 1)

            subs_pattern = '<a href="(#\d+)"'
            replacement = '<a href="'+ request.build_absolute_uri() +'\g<1>"'
            text = re.sub(subs_pattern, replacement, text)

            pattern = '<tr><td bgcolor="#00Ff00"><img border="0" src="/images/empty.gif" width="1" height="1"></td></tr>'
            text = re.sub(pattern, '', text, 2)
        else:
            text = u'Файл сценария не найден :('
    else:
        text = u'Просмотр сценария не разрешен.'

    return render_to_response('scenario.html',{'text':text, 'domain':domain, 'game':game, 'mybase':request.get_host(),})

def search(request):
    return render_to_response("serp.html", {})    